Skip to main content
summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
Diffstat (limited to 'bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text')
-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.java1648
-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.java63
-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.java368
-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.java209
-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
233 files changed, 0 insertions, 58097 deletions
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 e5d10e91..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaIndenter.java
+++ /dev/null
@@ -1,1648 +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:
- 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 72fc8ee8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/FieldProposalInfo.java
+++ /dev/null
@@ -1,63 +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.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 type= fJavaProject.findType(typeName);
- 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 80b66833..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, 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
- * 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("class ____C{void ____m()"); //$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 83ea90c2..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, 2008 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.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" //$NON-NLS-1$
- };
-
-// 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 e54a6488..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaTypeCompletionProposal.java
+++ /dev/null
@@ -1,368 +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.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= getQualifiedTypeName();
- 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());
- }
-
- /*
- * @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 getSimpleTypeName() + Character.MIN_VALUE + 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 a29e171e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MethodProposalInfo.java
+++ /dev/null
@@ -1,209 +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.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();
-
- if (declarationSignature!=null) {
- String typeName = SignatureUtil.stripSignatureToFQN(String
- .valueOf(declarationSignature));
- String name = String.valueOf(fProposal.getName());
- String[] parameters = Signature.getParameterTypes(String
- .valueOf(fProposal.getSignature()));
- IType type = fJavaProject.findType(typeName);
- if (type != null) {
- boolean isConstructor = fProposal.isConstructor();
-
- return findMethod(name, parameters, isConstructor, type);
- }
- else
- {
- ITypeRoot typeRoot=fJavaProject.findTypeRoot(typeName);
- if(typeRoot != null)
- return typeRoot.getFunction(name, parameters);
- }
- }
- return null;
- }
-
- /* 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 1d17ac49..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, 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.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.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 12c13011..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, 2008 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is 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 null;
- }
-
- 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;
- }
-}

Back to the top